package com.student.servie;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.student.common.Result;
import com.student.dao.entity.StClass;
import com.student.dao.entity.StDorm;
import com.student.dao.entity.StMajor;
import com.student.dao.entity.StUser;
import com.student.dao.mapper.StDormMapper;
import com.student.dao.mapper.StMajorMapper;
import com.student.dao.service.IStClassService;
import com.student.dao.service.IStDormService;
import com.student.dao.service.IStMajorService;
import com.student.dao.service.IStUserService;
import com.student.vo.VoElement;
import com.student.vo.VoUser;
import org.apache.commons.lang3.text.StrTokenizer;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author 李123
 */
@Service
public class StudentService {
    //头像图片上传地址
    @Value("${stuImgFile}")
    private String imgFile;

    @Autowired
    private IStMajorService majorService;
    @Autowired
    private IStClassService classService;
    @Autowired
    private IStDormService dormService;
    @Autowired
    private IStUserService userService;
    @Autowired
    private AdminService adminService;

    @Autowired
    private StDormMapper stDormMapper;

    @Autowired
    private StMajorMapper stMajorMapper;

    @Autowired
    private IStClassService stClassService;


    /**
     * 构造全部专业班级数据结构
     */
    public Result getMajorClass() {
        LinkedList<VoElement<Long>> resList = new LinkedList<>();
        List<StMajor> majorList = majorService.list();
        for (StMajor major : majorList) {
            VoElement<Long> tem = new VoElement<>();
            LinkedList<VoElement<Long>> temList = new LinkedList<>();
            List<StClass> classList = classService.list(new QueryWrapper<StClass>().eq("major_id", major.getId()));
            for (StClass stClass : classList) {
                VoElement<Long> temVo = new VoElement<>();
                temVo.setLabel(stClass.getName());
                temVo.setValue(stClass.getId());
                temVo.setChildren(null);
                temList.add(temVo);
            }
            tem.setChildren(temList);
            tem.setValue(major.getId());
            tem.setLabel(major.getName());
            resList.add(tem);
        }
        return Result.succ(resList);
    }

    /**
     * 构造全部宿舍数据
     */
    public Result getDorm() {
        LinkedList<VoElement<Long>> resList = new LinkedList<>();
        List<StDorm> dormList = dormService.list();
        Map<String, LinkedList<VoElement<Long>>> map = new HashMap<>();
        for (StDorm dorm : dormList) {
            if (!map.containsKey(dorm.getDormAddress())) {
                map.put(dorm.getDormAddress(), new LinkedList<>());
            } else {
                VoElement<Long> tem = new VoElement<>(dorm.getId(), dorm.getDormNum(), null);
                map.get(dorm.getDormAddress()).add(tem);
            }
        }
        for(String key:map.keySet()) {
            resList.add(new VoElement<>(0L, key, map.get(key)));
        }
        return Result.succ(resList);
    }

    /**
     * 更新学生信息
     */
    public Result updateStu(VoUser voUser){
        return adminService.updateStu(voUser);
//        StUser stUser = new StUser();
//        //对象转换
//        BeanUtils.copyProperties(voUser,stUser);
//        stUser.setMajorClassId(Long.valueOf(voUser.getMajorClass()[1].toString()));
//        stUser.setMajorId((Long.valueOf(voUser.getMajorClass()[0].toString())));
//        stUser.setDormId((Long.valueOf(voUser.getDorm()[1].toString())));
//        //更新数据库
//        if(userService.updateById(stUser)){
//            return Result.succ(null);
//        }else {
//            return Result.fail("完善信息失败");
//        }
    }

    /**
     * 更改用户头像
     */
    public Result upAvatar(MultipartFile file){
        StUser user= (StUser) SecurityUtils.getSubject().getPrincipal();
        String oriFilename= file.getOriginalFilename();
        //用uuid构造唯一文件名
        String newFilename= UUID.randomUUID()+"-"+user.getUsername()+"-"+oriFilename;
        //文件路径
        File filePath = new File(imgFile);
        if(!filePath.exists()){
            if(!filePath.mkdirs()) {
                return Result.fail("文件路径创建失败");
            }
        }
        //删除旧文件
        String oldFilename=user.getAvatar();
        if(!"userImg.png".equals(oldFilename)){
            File oldFile=new File(imgFile+user.getAvatar());
            if(!oldFile.exists()||!oldFile.delete()){
                return Result.fail("原有图片移除失败");
            }
        }
        //上传新文件
        try {
            file.transferTo(new File(imgFile+newFilename));
        } catch (IOException e) {
            return Result.succ("图片上传失败");
        }
        //更新数据库
        StUser stUser=new StUser();
        stUser.setAvatar(newFilename);
        stUser.setId(user.getId());
        if(userService.updateById(stUser)){
            return Result.succ(newFilename);
        }else {
            return Result.fail("图片上传失败");
        }

    }

    public Integer saveStudents(MultipartFile file) {

        try {
            // 加载 Excel 文件
            InputStream inputStream = file.getInputStream();
            Workbook workbook = new XSSFWorkbook(inputStream);

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);

            //统计新增个数
            int count = 0;
            // 遍历工作表的行，并将数据保存到数据库
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                Row row = sheet.getRow(rowIndex);
                if (row != null) {
                    StUser stUser = new StUser();

                    //获取行 数据
                    // 获取每个单元格的数据
                    Cell usernameCell = row.getCell(0);
                    String username = "";
                    if (usernameCell != null) {
                        if (usernameCell.getCellType() == CellType.STRING) {
                            username = usernameCell.getStringCellValue();
                        } else if (usernameCell.getCellType() == CellType.NUMERIC) {
                            double numericValue = usernameCell.getNumericCellValue();
                            username = String.valueOf(numericValue);
                        }
                    }
                    stUser.setRealName(username);

                    Cell schoolNumberCell = row.getCell(1);
                    String schoolNumber = "";
                    if (schoolNumberCell != null) {
                        if (schoolNumberCell.getCellType() == CellType.STRING) {
                            schoolNumber = schoolNumberCell.getStringCellValue();
                        } else if (schoolNumberCell.getCellType() == CellType.NUMERIC) {
                            double numericValue = schoolNumberCell.getNumericCellValue();
                            schoolNumber = String.valueOf((long) numericValue);
                        }
                    }
                    stUser.setUsername(schoolNumber);

                    // 继续处理其他单元格的数据
                    Cell phoneCell = row.getCell(2);
                    String phone = "";
                    if (phoneCell != null) {
                        if (phoneCell.getCellType() == CellType.STRING) {
                            phone = phoneCell.getStringCellValue();
                        } else if (phoneCell.getCellType() == CellType.NUMERIC) {
                            double numericValue = phoneCell.getNumericCellValue();
                            phone = String.valueOf((long) numericValue);
                        }
                    }
                    stUser.setPhoneNum(phone);

                    Cell ageCell = row.getCell(3);
                    String age = "";
                    if (ageCell != null) {
                        if (ageCell.getCellType() == CellType.STRING) {
                            age = ageCell.getStringCellValue();
                        } else if (ageCell.getCellType() == CellType.NUMERIC) {
                            double numericValue = ageCell.getNumericCellValue();
                            age = String.valueOf((long)numericValue);
                        }
                    }
                    stUser.setAge(age);

                    Cell sexCell = row.getCell(4);
                    String sex = "";
                    if (sexCell != null) {
                        if (sexCell.getCellType() == CellType.STRING) {
                            sex = sexCell.getStringCellValue();
                        } else if (sexCell.getCellType() == CellType.NUMERIC) {
                            double numericValue = sexCell.getNumericCellValue();
                            sex = String.valueOf(numericValue);
                        }
                    }
                    stUser.setSex(sex);

                    Cell documentNumberCell = row.getCell(5);
                    String documentNumber = "";
                    if (documentNumberCell != null) {
                        if (documentNumberCell.getCellType() == CellType.STRING) {
                            documentNumber = documentNumberCell.getStringCellValue();
                        } else if (documentNumberCell.getCellType() == CellType.NUMERIC) {
                            double numericValue = documentNumberCell.getNumericCellValue();
                            documentNumber = String.valueOf(numericValue);
                        }
                    }
                    stUser.setIdCard(documentNumber);

                    //截取宿舍地址字段
                    String addressNum = row.getCell(6).getStringCellValue();
                    String address = addressNum.substring(0,2);
                    String num = addressNum.substring(2);
                    //查出对应的id
                    LambdaQueryWrapper<StDorm> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(StDorm::getDormNum, num);
                    queryWrapper.eq(StDorm::getDormAddress, address);
                    StDorm stDorm = stDormMapper.selectOne(queryWrapper);
                    stUser.setDormId(stDorm.getId());


                    Cell timeCell = row.getCell(7);
                    String time = "";
                    if (timeCell != null) {
                        if (timeCell.getCellType() == CellType.STRING) {
                            time = timeCell.getStringCellValue();
                        } else if (timeCell.getCellType() == CellType.NUMERIC) {
                            double numericValue = timeCell.getNumericCellValue();
                            time = String.valueOf(numericValue);
                        }
                    }
                    stUser.setStuDay(time);

                    Cell professionClassCell = row.getCell(8);
                    String professionClass = "";
                    if (professionClassCell != null) {
                        if (professionClassCell.getCellType() == CellType.STRING) {
                            professionClass = professionClassCell.getStringCellValue();
                        } else if (professionClassCell.getCellType() == CellType.NUMERIC) {
                            double numericValue = professionClassCell.getNumericCellValue();
                            professionClass = String.valueOf(numericValue);
                        }
                    }

                    String[] professionClassSplit = professionClass.split("/");
                    String profession = professionClassSplit[0];
                    String studentClass = professionClassSplit[1];
                    LambdaQueryWrapper<StMajor> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(StMajor::getName,profession);
                    StMajor stMajor = stMajorMapper.selectOne(wrapper);

                    LambdaQueryWrapper<StClass> stClassLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    stClassLambdaQueryWrapper.eq(StClass::getMajorId,stMajor.getId()).eq(StClass::getName,studentClass);
                    StClass stClass = stClassService.getOne(stClassLambdaQueryWrapper);
                    stUser.setMajorId(stMajor.getId());
                    stUser.setMajorClassId(stClass.getId());

                    //设置盐、密码（默认为身份证后六位）
                    adminService.initPassword(stUser);
                    stUser.setRoleId(1L);

                    //邮件待完善
                    stUser.setEmail("待完善");
                    boolean isSave = userService.save(stUser);

                    if (isSave){
                        count ++;
                    }
                }
            }
            return count;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
